package org.jeecg.modules.cw.controller;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.druid.util.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.cw.entity.CwApprovalMessage;
import org.jeecg.modules.cw.entity.CwCzjb;
import org.jeecg.modules.cw.service.ICwApprovalMessageService;
import org.jeecg.modules.cw.service.ICwCzjbService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 财政基本
 * @Author: jeecg-boot
 * @Date:   2025-10-21
 * @Version: V1.0
 */
@Api(tags="财政基本")
@RestController
@RequestMapping("/cw/cwCzjb")
@Slf4j
public class CwCzjbController extends JeecgController<CwCzjb, ICwCzjbService> {
	@Autowired
	private ICwCzjbService cwCzjbService;
	 @Autowired
	 private ICwApprovalMessageService cwApprovalMessageService;
	 @Autowired
	 private ISysDepartService sysDepartService;
	 @Autowired
	 private ISysBaseAPI iSysBaseAPI;
	/**
	 * 分页列表查询
	 *
	 * @param cwCzjb
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "财政基本-分页列表查询")
	@ApiOperation(value="财政基本-分页列表查询", notes="财政基本-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<CwCzjb>> queryPageList(CwCzjb cwCzjb,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<CwCzjb> queryWrapper = QueryGenerator.initQueryWrapper(cwCzjb, req.getParameterMap());
		Page<CwCzjb> page = new Page<CwCzjb>(pageNo, pageSize);
		// 获取登录用户信息
		LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		if (user == null || StringUtils.isEmpty(user.getId())) {
			return Result.error("未获取到登录用户信息，查询失败");
		}
		String currentUserId = user.getId();

		// 获取用户所属部门名称（departName）
		String departIdsByOrgCode = iSysBaseAPI.getDepartIdsByOrgCode(user.getOrgCode());
		SysDepart depart = sysDepartService.getById(departIdsByOrgCode);
		if (depart == null || StringUtils.isEmpty(depart.getDepartName())) {
			return Result.error("未获取到用户所属部门信息，查询失败");
		}
		String departName = depart.getDepartName(); // 用户所属部门名称

		// 定义特权用户ID
		String admin1 = "1985179654538330114";  // 第一个特权用户（拥有待审批权限）
		String admin2 = "1985180799365218306";  // 第二个特权用户
		String admin3 = "1985180919854989314";  // 第三个特权用户

// 定义需要过滤的部门（机关、鉴定站）
		List<String> allowedDepartments = Arrays.asList("机关", "鉴定站");
		if (admin1.equals(currentUserId)) {
			// 第一个特权用户：
			// 1. 待审批状态仅查询“机关”和“鉴定站”部门
			// 2. 其他状态（通过、驳回、第一人审批同意）无部门限制
			queryWrapper.and(wrapper -> wrapper
					// 待审批 + 限定部门
					.or().eq("status", "待审批").in("unit", allowedDepartments)
					// 其他状态无部门限制
					.or().in("status", "通过", "驳回", "第一人审批同意")
			);
		} else if (admin2.equals(currentUserId) || admin3.equals(currentUserId)) {
			// 第二、三个特权用户：仅可查询通过、驳回
			queryWrapper.in("status", "通过", "驳回","第一人审批同意");
		} else {
			// 非特权用户：仅查询unit等于其所属部门名称的数据
			queryWrapper.eq("unit", departName);
		}
		IPage<CwCzjb> pageList = cwCzjbService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	 /**
	  * 单个提交审核
	  * @param id 数据ID
	  * @param status 状态（已提交）
	  * @return 操作结果
	  */
	 @AutoLog(value = "财政基本-单个提交审核")
	 @ApiOperation(value="财政基本-单个提交审核", notes="财政基本-单个提交审核")
	 @RequestMapping(value = "/approval", method = {RequestMethod.PUT, RequestMethod.POST})
	 public Result<String> approval(@RequestParam(name = "id", required = true) String id,
									@RequestParam(name = "approvalResult", required = true) String approvalResult,
									@RequestParam String approvalRemark) {
		 //获取当前用户名
		 LoginUser user= (LoginUser)SecurityUtils.getSubject().getPrincipal();
		 String userId=user.getId();
		 CwCzjb czjb = cwCzjbService.getById(id);
		 if (czjb == null) {
			 return Result.error("数据不存在");
		 }
		 if ("通过".equals(approvalResult)) {
			 if ("1985179754371153921".equals(userId)||"1985179977394880513".equals(userId)||
					 "1985180115760775170".equals(userId)||"1985180266818633730".equals(userId)
					 ||"1985180455415513090".equals(userId)){
				 czjb.setStatus("第一人审批同意");
			 }else {
				 czjb.setStatus(approvalResult);
			 }
		 }else {
			 czjb.setStatus(approvalResult);
		 }
		 cwCzjbService.updateById(czjb);
		 CwApprovalMessage cwApprovalMessage = new CwApprovalMessage();
		 cwApprovalMessage.setMainId(id);
		 cwApprovalMessage.setApprovalMessage(approvalRemark);
		 cwApprovalMessage.setApprovalTime(new Date());
		 cwApprovalMessage.setApprover(userId);
		 cwApprovalMessage.setState(approvalResult);
		 cwApprovalMessage.setSpr(user.getRealname());
		 cwApprovalMessageService.save(cwApprovalMessage);
		 return Result.OK("提交审核成功");
	 }

	 /**
	  * 批量提交审核
	  * @param ids 数据ID集合（逗号分隔）
	  * @param status 状态（已提交）
	  * @return 操作结果
	  */
	 @AutoLog(value = "财政基本-批量提交审核")
	 @ApiOperation(value="财政基本-批量提交审核", notes="财政基本-批量提交审核")
	 @RequestMapping(value = "/batchApproval", method = {RequestMethod.PUT, RequestMethod.POST})
	 public Result<String> batchApproval(@RequestParam(name = "ids", required = true) String ids,
										 @RequestParam(name = "approvalResult", required = true) String approvalResult,
										 @RequestParam String approvalRemark) {
		 //获取当前用户名
		 LoginUser user= (LoginUser)SecurityUtils.getSubject().getPrincipal();
		 String userId=user.getId();
		 List<String> idList = Arrays.asList(ids.split(","));
		 if (idList.isEmpty()) {
			 return Result.error("请选择要提交的数据");
		 }
		 for (String id : ids.split(",")) {
			 CwApprovalMessage cwApprovalMessage = new CwApprovalMessage();
			 cwApprovalMessage.setMainId(id);
			 cwApprovalMessage.setApprovalMessage(approvalRemark);
			 cwApprovalMessage.setApprovalTime(new Date());
			 cwApprovalMessage.setApprover(userId);
			 cwApprovalMessage.setState(approvalResult);
			 cwApprovalMessage.setSpr(user.getRealname());
			 cwApprovalMessageService.save(cwApprovalMessage);
		 }
		 // 批量更新状态
		 CwCzjb updateEntity = new CwCzjb();
		 if ("通过".equals(approvalResult)) {
			 if ("1985179754371153921".equals(userId)||"1985179977394880513".equals(userId)||
					 "1985180115760775170".equals(userId)||"1985180266818633730".equals(userId)
					 ||"1985180455415513090".equals(userId)){
				 updateEntity.setStatus("第一人审批同意");
			 }else {
				 updateEntity.setStatus(approvalResult);
			 }
		 }else {
			 updateEntity.setStatus(approvalResult);
		 }
		 cwCzjbService.update(updateEntity, new QueryWrapper<CwCzjb>().in("id", idList));
		 return Result.OK("批量提交审核成功");
	 }

	 /**
	 *   添加
	 *
	 * @param cwCzjb
	 * @return
	 */
	@AutoLog(value = "财政基本-添加")
	@ApiOperation(value="财政基本-添加", notes="财政基本-添加")
	//@RequiresPermissions("org.jeecg.modules:cw_czjb:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody CwCzjb cwCzjb) {
		LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		String departIdsByOrgCode = iSysBaseAPI.getDepartIdsByOrgCode(user.getOrgCode());
		SysDepart byId = sysDepartService.getById(departIdsByOrgCode);
		String departName = byId.getDepartName();
		cwCzjb.setUnit(departName);
		cwCzjb.setMainId(user.getId());
		cwCzjb.setStatus("待提交");
		cwCzjbService.save(cwCzjb);
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param cwCzjb
	 * @return
	 */
	@AutoLog(value = "财政基本-编辑")
	@ApiOperation(value="财政基本-编辑", notes="财政基本-编辑")
	//@RequiresPermissions("org.jeecg.modules:cw_czjb:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody CwCzjb cwCzjb) {
		LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		CwCzjb byId = cwCzjbService.getById(cwCzjb.getId());
		String departIdsByOrgCode = iSysBaseAPI.getDepartIdsByOrgCode(user.getOrgCode());
		SysDepart byId1 = sysDepartService.getById(departIdsByOrgCode);
		String departName = byId1.getDepartName();
		cwCzjb.setUnit(departName);
		cwCzjb.setStatus(byId.getStatus());
		cwCzjb.setMainId(user.getId());
		cwCzjbService.updateById(cwCzjb);
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "财政基本-通过id删除")
	@ApiOperation(value="财政基本-通过id删除", notes="财政基本-通过id删除")
	//@RequiresPermissions("org.jeecg.modules:cw_czjb:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		cwCzjbService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "财政基本-批量删除")
	@ApiOperation(value="财政基本-批量删除", notes="财政基本-批量删除")
	//@RequiresPermissions("org.jeecg.modules:cw_czjb:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.cwCzjbService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "财政基本-通过id查询")
	@ApiOperation(value="财政基本-通过id查询", notes="财政基本-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<CwCzjb> queryById(@RequestParam(name="id",required=true) String id) {
		CwCzjb cwCzjb = cwCzjbService.getById(id);
		if(cwCzjb==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(cwCzjb);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param cwCzjb
    */
    //@RequiresPermissions("org.jeecg.modules:cw_czjb:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, CwCzjb cwCzjb) {
        return super.exportXls(request, cwCzjb, CwCzjb.class, "财政基本");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    //@RequiresPermissions("cw_czjb:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, CwCzjb.class);
    }

	 /**
	  * 单个提交审核
	  * @param id 数据ID
	  * @param status 状态（已提交）
	  * @return 操作结果
	  */
	 @AutoLog(value = "财政基本-单个提交审核")
	 @ApiOperation(value="财政基本-单个提交", notes="财政基本-单个提交")
	 @RequestMapping(value = "/submitSingle", method = {RequestMethod.PUT, RequestMethod.POST})

	 public Result<String> submitSingle(@RequestParam(name="id", required=true) String id,
										@RequestParam(name="status", required=true) String status) {
		 CwCzjb czjb = cwCzjbService.getById(id);
		 if (czjb == null) {
			 return Result.error("数据不存在");
		 }
		 czjb.setStatus(status);
		 cwCzjbService.updateById(czjb);
		 return Result.OK("提交审核成功");
	 }

	 /**
	  * 批量提交审核
	  * @param ids 数据ID集合（逗号分隔）
	  * @param status 状态（已提交）
	  * @return 操作结果
	  */
	 @AutoLog(value = "财政基本-批量提交审核")
	 @ApiOperation(value="财政基本-批量提交审核", notes="财政基本-批量提交审核")
	 @RequestMapping(value = "/batchSubmit", method = {RequestMethod.PUT, RequestMethod.POST})
	 public Result<String> batchSubmit(@RequestParam(name="ids", required=true) String ids,
									   @RequestParam(name="status", required=true) String status) {
		 List<String> idList = Arrays.asList(ids.split(","));
		 if (idList.isEmpty()) {
			 return Result.error("请选择要提交的数据");
		 }
		 // 批量更新状态
		 CwCzjb updateEntity = new CwCzjb();
		 updateEntity.setStatus(status);
		 cwCzjbService.update(updateEntity, new QueryWrapper<CwCzjb>().in("id", idList));
		 return Result.OK("批量提交审核成功");
	 }

	 /**
	  * 全部提交审核
	  * @param status 状态（已提交）
	  * @return 操作结果
	  */
	 @AutoLog(value = "财政基本-全部提交审核")
	 @ApiOperation(value="财政基本-全部提交审核", notes="财政基本-全部提交审核")
	 @PutMapping(value = "/submitAll")
	 public Result<String> submitAll(@RequestParam(name="status", required=true) String status) {
		 // 更新所有数据状态
		 CwCzjb updateEntity = new CwCzjb();
		 updateEntity.setStatus(status);
		 cwCzjbService.update(updateEntity, new QueryWrapper<CwCzjb>());
		 return Result.OK("全部数据提交审核成功");
	 }

}
